package com.example.demo.gw.route;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class DynamicRouteService {

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    @Autowired
    private ApplicationEventPublisher publisher;

    public void updateRoutes(List<RouteDefinition> definitions) {
        definitions.forEach(definition -> {
            routeDefinitionWriter.delete(Mono.just(definition.getId())).subscribe();
            routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        });
        publisher.publishEvent(new RefreshRoutesEvent(this));
    }

}
